package com.dbappsecurity.bifrost.base;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import butterknife.Unbinder;
import com.dbappsecurity.bifrost.BifrostApp;
import com.dbappsecurity.bifrost.contract.BaseContract;
import com.dbappsecurity.bifrost.di.component.ActivityComponent;
import com.dbappsecurity.bifrost.di.component.DaggerActivityComponent;
import com.dbappsecurity.bifrost.di.module.ActivityModule;
import com.dbappsecurity.bifrost.receiver.MyReceiver;
import com.dbappsecurity.bifrost.view.MainActivity;
import com.dbappsecurity.bifrost.view.SplashActivity;
import com.dbappsecurity.core.CoreBaseActivity;
import com.dbappsecurity.network.Thunder;
import com.tbruyelle.rxpermissions2.RxPermissions;
import dagger.Lazy;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.inject.Inject;

abstract public class InjectBaseActivity extends CoreBaseActivity implements BaseContract.View {

  protected ActivityComponent mActivityComponent;

  @Inject protected Lazy<Thunder> mApiClient;

  @Inject protected Lazy<StringBuilder> mBuilder;

  @Inject protected Unbinder mUnBinder;

  @Inject protected Lazy<CompositeDisposable> mDisposables;

  @Inject protected Lazy<FragmentManager> fragmentManager;

  @Inject protected Lazy<RxPermissions> permissions;

  @Override
  protected void onViewCreated(Intent source, Bundle savedInstanceState) {
    mActivityComponent = DaggerActivityComponent.builder()
        .app(BifrostApp.sAppComponent)
        .base(new ActivityModule(this))
        .setContractView(this)
        .build();

    try {
      Method method = ActivityComponent.class.getDeclaredMethod("inject",getClass());
      method.invoke(mActivityComponent,this);
    } catch (NoSuchMethodException e) {
      e.printStackTrace();
      mActivityComponent.inject(this);
    } catch (IllegalAccessException e) {
      e.printStackTrace();
    } catch (InvocationTargetException e) {
      e.printStackTrace();
    }
  }
  @Override
  protected void onResume() {
    super.onResume();
    MyReceiver.badgeCount = 0;
  }

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (mUnBinder != null) mUnBinder.unbind();
    if (mDisposables != null) mDisposables.get().clear();
    mActivityComponent = null;
  }

  protected void addDisposable(Disposable disposable) {
    if (mDisposables != null) mDisposables.get().add(disposable);
  }

  protected void removeDisposable(Disposable disposable) {
    if (mDisposables != null) {
      mDisposables.get().remove(disposable);
    }
  }
}
